#!/usr/bin/env python
# -*- coding: utf-8 -*-

from jujud.jujud import Server

from cache import Cache
from jupacket import decodeRequest,encodeResponse

import log


#######################################################################

class CacheServer(Server)  :
    '''Cache Server'''

    def __init__(self, store_path, n_cells=1) :
        self._cache = Cache(store_path, n_cells)
        # __init__()

    def __del__(self) :
        if self._cache :
            del self._cache
            self._cache = None
        # __del__()

    def serve(self, service, request, address_from) :
        if log.debugable :
            log.debug('SERVICE "%s" echo "%s" from "%s"', service, request, address_from)

        packet = decodeRequest(request)

        if packet.isInsertAction() :
            _status = self._cache.insert(packet.key, packet.data, packet.timeout)
            packet.status = _status
        elif packet.isEraseAction() :
            _status = self._cache.erase(packet.key)
            packet.status = _status
        elif packet.isLookupAction() :
            _status, _data = self._cache.lookup(packet.key)
            packet.status = _status
            packet.data = _data

        # response
        packet.setResponse()
        response = encodeResponse(packet)
        address_to = address_from
        return service, response, address_to
        # serve()
    # class CacheServer

